package com.hh.front.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.hh.common.exception.HhException;
import com.hh.common.utils.RedisUtil;
import com.hh.common.utils.RestTemplateUtil;
import com.hh.front.dto.UserPhoneInfoDto;
import com.hh.front.dto.WxGetAccessTokenErrorResult;
import com.hh.front.dto.WxMaJscodeResultErrorResult;
import com.hh.front.service.WxUserMaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WxUserMaServiceImpl implements WxUserMaService {

    private static final String ACCESS_TOKEN_PREFIX = "wx_access_token:";

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取access_token.
     */
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    /**
     * The constant JSCODE_TO_SESSION_URL.
     */
    private static final String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * getPaidUnionId
     */
    private static final String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid";

    private static final String GET_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";

    /**
     * 导入抽样数据
     */
    private static final String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata";

    @Override
    public WxMaJscodeResultErrorResult getSessionInfo(Map<String, String> params) {

        String uri = JSCODE_TO_SESSION_URL + "?grant_type=authorization_code&" +Joiner.on("&").withKeyValueSeparator("=").join(params);
        String s = restTemplateUtil.getData(uri).toString();
        WxMaJscodeResultErrorResult wxMaJscodeResult = JSONObject.parseObject(s, WxMaJscodeResultErrorResult.class);
        if(null != wxMaJscodeResult.getErrcode()){
            throw new ClassCastException(wxMaJscodeResult.getErrmsg());
        }
        return wxMaJscodeResult;
    }

    @Override
    public String getNewPhoneNoInfo(String code,String appId,String secret) {
        
        //获取access_token
        String access_token = redisUtil.get(ACCESS_TOKEN_PREFIX + appId);

        if(StrUtil.isBlank(access_token)){
            String uri = String.format(GET_ACCESS_TOKEN_URL, appId, secret);
            JSONObject data = restTemplateUtil.getData(uri);
            String s = data.toString();
            WxGetAccessTokenErrorResult wxGetAccessTokenErrorResult = JSONObject.parseObject(s,WxGetAccessTokenErrorResult.class);

            if(null != wxGetAccessTokenErrorResult.getErrcode()){
                throw new HhException(wxGetAccessTokenErrorResult.getErrmsg());
            }
            access_token = wxGetAccessTokenErrorResult.getAccessToken();
            long exp = wxGetAccessTokenErrorResult.getExpiresIn() - 300;
            redisUtil.set(ACCESS_TOKEN_PREFIX + appId,access_token,exp);

        }
        String format = String.format(GET_USER_PHONE_URL, access_token);
        JSONObject param = new JSONObject();
        param.put("code",code);
        String s = restTemplateUtil.postStringData(format, param.toString());
        JSONObject jsonObject = JSONObject.parseObject(s);

        Object phone_info = jsonObject.get("phone_info");
        UserPhoneInfoDto userPhoneInfoDto = JSON.parseObject(JSON.toJSONString(phone_info), UserPhoneInfoDto.class);

        if(ObjectUtil.isNull(userPhoneInfoDto)){
            throw new HhException("获取手机号失败");
        }

        return userPhoneInfoDto.getPhoneNumber();


    }
}
